<?php

namespace app\service\Web;

use app\model\News;
use Exception;
use app\util\GlobalCode;
use app\util\GlobalMsg;
//use Illuminate\Support\Facades\DB;
use support\Db;

class NewsService
{

    public static function getList(array $where = [], int $page = 0, int $pageSize = 0)
    {
        $news = News::with(['news_cate']);

        if (!empty($where['is_show'])) {
            $news = $news->where('is_show', $where['is_show']);
        }
        if (!empty($where['lang'])) {
            $news = $news->where('lang', $where['lang']);
        }
        if (!empty($where['news_cate_id'])) {
            $news = $news->where('news_cate_id', $where['news_cate_id']);
        }
        if (!empty($where['platform'])) {
            $news = $news->where('platform', $where['platform']);
        }

        $count = $news->count();

        if ($page > 0 && $pageSize > 0) {
            $news = $news->forPage($page, $pageSize);
        }

        $list = $news->orderBy('sort', 'asc')->orderBy('id', 'desc')->get()->toArray();

        return ['count' => $count, 'list' => $list];
    }

    public static function getOne(int $id = 0)
    {
        $news = News::where('id', $id)->first();
        if ($news == null) {
            throw new Exception(GlobalMsg::GET_HAS_NO);
        }
        return $news;
    }

    public static function getInfo(int $id = 0,array $where = []){
        $bindings = [];
        $sql = 'SELECT 
                        curr.*,
                        prev.id AS prev_id,
                        prev.title AS prev_title,
                        next.id AS next_id,
                        next.title AS next_title
                    FROM news curr
                    LEFT JOIN (
                        SELECT n1.* FROM news n1
                        WHERE (n1.sort < (SELECT sort FROM news WHERE id = ?))
                           OR (n1.sort = (SELECT sort FROM news WHERE id = ?) AND n1.id > ?)
                        ORDER BY n1.sort ASC, n1.id DESC
                        LIMIT 1
                    ) prev ON 1=1
                    LEFT JOIN (
                        SELECT n2.* FROM news n2
                        WHERE (n2.sort > (SELECT sort FROM news WHERE id = ?))
                           OR (n2.sort = (SELECT sort FROM news WHERE id = ?) AND n2.id < ?)
                        ORDER BY n2.sort ASC, n2.id DESC
                        LIMIT 1
                    ) next ON 1=1
                    WHERE curr.id = ?';
        $bindings = [$id,$id,$id,$id,$id,$id,$id];
        if (!empty($where['news_cate_id'])) {
            $sql .= ' and curr.news_cate_id = ?';
            $bindings[] = $where['news_cate_id'];
        }

        $news = DB::select($sql.';',$bindings);
        if ($news == null) {
            throw new Exception(GlobalMsg::GET_HAS_NO);
        }
        return $news;
    }
}
